package com.xingchen.loveparttimejob.controller.servlet;

import com.google.gson.GsonBuilder;
import com.xingchen.loveparttimejob.model.vo.ResponseData;
import com.xingchen.loveparttimejob.uitls.JSONUtil;
import com.xingchen.loveparttimejob.uitls.ResponseDataUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.io.IOException;
import java.io.PrintWriter;

/**
 * 它是所有的用户定义Servlet的父类 - 把一些公共操作的代码，抽象提取出来，在父类中定义，子类可以直接使用
 *
 * @author zqx
 * @date 2022-12-02
 */
public class BaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;




    /**
     * 成功响应的封装 - 默认
     *
     * @return
     */
    public ResponseData successJson(Object data) {
        return ResponseDataUtils.generateResponseData(200,"success","",data);
    }

    /**
     * 重载方法 - 封装所有的成功响应信息
     *
     * @param code
     * @param msg
     * @param data
     * @return
     */
    public ResponseData successJson(Integer code,String type, String msg, Object data) {
        return ResponseDataUtils.generateResponseData(code,type,msg,data);
    }

    /**
     * 错误响应的封装 - 默认
     *
     * @param msg
     * @return
     */
    public ResponseData errorJson(String msg) {
        return ResponseDataUtils.generateResponseData(500,"error",msg,null);
    }

    /**
     * 重载方法 - 封装所有的错误响应信息
     *
     * @param code
     * @param msg
     * @param data
     * @return
     */
    public ResponseData errorJson(Integer code,String type, String msg, Object data) {
        return ResponseDataUtils.generateResponseData(code,type,msg,data);
    }


    /**
     * 响应 JSON 字符串到客户端浏览器中
     *
     * @param response
     * @param responseData
     * @throws IOException
     */
    protected void print(HttpServletResponse response, ResponseData responseData) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(JSONUtil.getObjectJson(responseData,ResponseData.class));
        out.flush();
        out.close();
    }
}
